﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Budget.DataAccess.Repository;

namespace Budget.DataAccess.Services
{
	public class IncomeDataService : IIncomeDataService
	{
		private IRepository<Income> repo;

		public IncomeDataService( IRepository<Income> repository )
		{
			repo = repository;
		}

		public IList<Income> GetAll()
		{
			IList<Income> incomes;

			using ( repo )
			{
				incomes = ( from i in repo.Query()
							orderby i.Description
							select i ).ToList();
			}

			return incomes;
		}

		public Income GetById( int ID )
		{
			Income income;

			using ( repo )
			{
				income = repo.Query().Where( i => i.IncomeId == ID ).FirstOrDefault();

				//var unfiltered = sRepo.Query();
				//income = ( from i in unfiltered
				//           where i.IncomeId == ID
				//           select i ).FirstOrDefault();
			}

			return income;
		}

		public void Save( Income entity )
		{
			using ( repo )
			{
				if ( entity.IncomeId > 0 )
				{
					repo.Attach( entity );
				}
				else
				{
					repo.Add( entity );
				}

				repo.SubmitChanges();
			}
		}

		public decimal GetTotalIncome()
		{
			decimal totalIncome = 0m;

			using ( repo )
			{
				totalIncome = repo.Query().Where( i => i.IsActive ).Sum( i => i.Amount );
			}

			return totalIncome;
		}
	}
}
